package core

import (
	"biliClient/global"
	"io/ioutil"
	"net/http"
	"strings"

	"github.com/tidwall/gjson"
)

//PlayURL ...
func PlayURL(roomID string) []string {
	req, _ := http.NewRequest("GET", "https://api.live.bilibili.com/xlive/web-room/v1/playUrl/playUrl", nil)
	param := req.URL.Query()
	param.Set("cid", roomID)
	param.Set("platform", "h5")
	param.Set("otype", "json")
	param.Set("quality", "0")
	param.Set("qn", "80")
	req.URL.RawQuery = param.Encode()
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		global.Log.Error(err)
		return nil
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		global.Log.Error(err)
		return nil
	}
	if resp.StatusCode != 200 {
		global.Log.Errorf("code:%v   %v\n", resp.StatusCode, string(body))
		return nil
	}
	durlArray := gjson.Get(string(body), "data.durl").Array()
	URLS := make([]string, 0)
	for _, i := range durlArray {
		URLS = append(URLS, i.Get("url").String())
	}
	return URLS
}

//GetM3U8 ...获取m3u8视频地址
func GetM3U8(playURL []string) string {
	for _, URL := range playURL {
		resp, err := http.Get(URL)
		if err != nil {
			global.Log.Error(err)
			continue
		}
		defer resp.Body.Close()
		body, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			global.Log.Error(err)
			continue
		}
		if resp.StatusCode != 200 {
			global.Log.Errorf("code:%v   %v\n", resp.StatusCode, string(body))
			continue
		}
		for _, i := range strings.Split(string(body), "\n") {
			if !strings.Contains(i, "#EXT") {
				if strings.Contains(i, "vhost") {
					if One(URL) {
						return URL
					}
				}
				if strings.Contains(i, "https") {
					if One(i) {
						return i
					}
				}
			}
		}
	}
	return ""
}

//One 测试连接
func One(m3u8 string) bool {
	tsURL := GetTsURL(m3u8)
	if tsURL == "" {
		return false
	}
	return PullM3U8Stream(tsURL)
}

//GetTsURL 获取TS链接
func GetTsURL(m3u8 string) string {
	resp, err := http.Get(m3u8)
	if err != nil {
		global.Log.Error(err)
		return ""
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		global.Log.Error(err)
		return ""
	}
	if resp.StatusCode != 200 {
		global.Log.Errorf("code:%v   %v\n", resp.StatusCode, string(body))
		return ""
	}
	var tsURL string
	for _, item := range strings.Split(string(body), "\n") {
		if !strings.Contains(item, "#EXT") {
			if len(item) != 0 {
				tsURL = ResolveURL(m3u8, item)
			}
		}
	}
	return tsURL
}

//ResolveURL ...拼接m3u8地址
func ResolveURL(m3u8, ts string) string {
	var (
		param string
		tsURL string
	)
	if strings.Contains(m3u8, "/live-bvc") {
		param = strings.Split(m3u8, "/live-bvc")[0]
		tsURL = param + ts
		return tsURL
	}
	if strings.Contains(m3u8, "/a.m3u8") {
		param = strings.Split(m3u8, "/a.m3u8")[0]
		tsURL = param + ts
		return tsURL
	}
	if strings.Contains(m3u8, "live_") {
		param = strings.Split(m3u8, "live_")[0]
		tsURL = param + ts
		return tsURL
	}
	return ""
}

//PullM3U8Stream ...拉流
func PullM3U8Stream(tsURL string) bool {
	resp, err := http.Get(tsURL)
	if err != nil {
		return false
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		global.Log.Errorf("%v\n", err)
	}
	if resp.StatusCode != 200 {
		global.Log.Errorf("code:%v   %v\n", resp.StatusCode, string(body))
		return false
	}
	return true
}
